<?php

class LoginQqClass {

	function __construct() {

		add_action('init', array($this, 'connect_init'), 1);
	}

	//QQ登录

	function connect_init() {
		if ($_GET['connect'] == 'qq') {
			$this -> login('qq');
		} elseif ($_GET['connect'] == 'qqbind') {
			if (!is_user_logged_in()) {
				wp_safe_redirect(home_url());
				exit ;
			}
			$this -> login('qqbind');
		} elseif ($_GET['callback'] == 'qqcallback') {
			$logintype = $_GET['logintype'];
			$this -> callback($logintype);
			if ($logintype == 'qqbind') {
				$this -> bind();
			} else {
				$this -> dispose();
			}
		} elseif ($_GET['connect'] == 'qqunwrap') {
			$this -> unwrap();
		}
	}

	//登录成功回调函数 目的就是获取访问令牌

	function login($type) {
		$_SESSION['rurl'] = $_REQUEST["r"];
		//~ 生成唯一随机串防CSRF攻击
		$_SESSION['state'] = md5(uniqid(rand(), true));
		$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" . new_option('qq_appid') . "&redirect_uri=" . urlencode(home_url('/') . "?callback=qqcallback&logintype=" . $type) . "&state=" . $_SESSION['state'] . "&scope=" . new_option('qq_appkey');
		header("Location:$login_url");
		exit ;
	}

	//~ 获取该QQ用户的openid
	function callback($type) {
		if ($_REQUEST['state'] == $_SESSION['state']) {
			$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&" . "client_id=" . new_option('qq_appid') . "&redirect_uri=" . urlencode(home_url('/') . "?callback=qqcallback&logintype=" . $type) . "&client_secret=" . new_option('qq_appkey') . "&code=" . $_REQUEST["code"];

			$response = get_url_contents($token_url);
			if (strpos($response, "callback") !== false) {
				$lpos = strpos($response, "(");
				$rpos = strrpos($response, ")");
				$response = substr($response, $lpos + 1, $rpos - $lpos - 1);
				$msg = json_decode($response);
				if (isset($msg -> error)) {
					exit('错误代码：' . $msg -> error . '<br/>错误信息：' . $msg -> error_description . '');
				}
			}

			$params = array();
			parse_str($response, $params);
			$_SESSION['access_token'] = $params["access_token"];
			$this -> get_openid($params["access_token"]);
		} else {
			exit('错误信息：CSRF不匹配。');
		}
	}

	//~ 获取用户信息

	function get_openid($token) {
		$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $token;

		$str = get_url_contents($graph_url);
		if (strpos($str, "callback") !== false) {
			$lpos = strpos($str, "(");
			$rpos = strrpos($str, ")");
			$str = substr($str, $lpos + 1, $rpos - $lpos - 1);
		}

		$user = json_decode($str);
		if (isset($user -> error)) {
			exit('错误代码：' . $user -> error . '<br/>错误信息：' . $user -> error_description . '');
		}
		$_SESSION['openid'] = $user -> openid;
	}

	//~ 登录后数据处理

	function bind() {
		if (!is_user_logged_in())
			exit('错误信息：请继续登录');
		global $wpdb;
		$session_uid = $_SESSION['openid'];
		$openid_db = $wpdb -> get_var("SELECT openid FROM `{$wpdb->users}` where openid='{$session_uid}'");
		if (empty($_SESSION['openid'])) {
			exit('错误信息：openid是空的');
		} elseif ($openid_db) {
			exit('错误信息：帐户已经绑定<a href="' . $_SESSION['rurl'] . '">点击返回</a>');
		} else {
			$userid = get_current_user_id();
			$wpdb -> query("UPDATE `{$wpdb->users}` SET openid = '{$_SESSION["openid"]}' WHERE ID = '{$userid}'");
			$uinfo = json_decode($this -> get_user_info());
			$qqimg = $uinfo -> figureurl_qq_2;
			$data = update_user_meta($userid, 'qquserimg', $qqimg);
			wp_redirect($_SESSION['rurl']);
			exit();
		}
	}

	//~ 绑定

	function get_user_info() {
		$get_user_info = "https://graph.qq.com/user/get_user_info?" . "access_token=" . $_SESSION['access_token'] . "&oauth_consumer_key=" . new_option('qq_appid') . "&openid=" . $_SESSION['openid'] . "&format=json";
		return get_url_contents($get_user_info);
	}

	//~ 解绑
	function dispose() {
		global $wpdb;
		if (empty($_SESSION['openid'])) {
			exit('错误信息：openid是空的');
		}
		$query = "SELECT ID FROM `{$wpdb->users}` where openid='{$_SESSION["openid"]}'";
		$openid_db = $wpdb -> get_var($query);
		if (is_numeric($openid_db)) {
			$user_ID = $openid_db;
			$user = get_user_by('id', $user_ID);
			wp_set_current_user($user_ID, $user -> user_login);
			wp_set_auth_cookie($user_ID);
			do_action('wp_login', $user -> user_login);
			wp_redirect($_SESSION['rurl']);
		} else {
			$login_name = wp_create_nonce($_SESSION['openid']);
			$pass = wp_create_nonce(microtime());
			$uinfo = json_decode($this -> get_user_info());
			$username = $uinfo -> nickname;
			$http = is_ssl() ? "https://" : "http://";
			$userdata = array('user_login' => $login_name, 'display_name' => $username, 'user_pass' => $pass, 'nickname' => $username, 'first_name' => $username, 'qquserimg' => $uinfo -> figureurl_qq_2, 'user_email' => $login_name . "@qq.com");
			$user_id = wp_insert_user($userdata);
			if (is_wp_error($user_id)) {
				exit('错误信息：' . $user_id -> get_error_message() . '<a href="' . $_SESSION['rurl'] . '">点击返回</a>');
			} else {
				$ff = $wpdb -> query("UPDATE `{$wpdb->users}` SET openid = '$_SESSION[openid]' WHERE ID = '$user_id'");
				if ($ff) {
					wp_set_current_user($user_id);
					wp_set_auth_cookie($user_id, true, false);
					wp_redirect($_SESSION['rurl']);
				}
			}
			exit();
		}
	}

	function unwrap() {
		global $wpdb;
		$userid = get_current_user_id();
		$wpdb -> query("UPDATE `{$wpdb->users}` SET openid = '' WHERE ID = '{$userid}'");
		delete_user_meta($userid, 'qquserimg');
	}

}
?>